package chapter12;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-23 下午2:37
 */
public class EchoThread implements Runnable {

    private Socket socket;

    public EchoThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        if (null == socket) {
            return;
        }
        try (Scanner input = new Scanner(socket.getInputStream());
             PrintStream output = new PrintStream(socket.getOutputStream())) {
            input.useDelimiter("\n");
            boolean flag = true;
            while (flag) {
                if (input.hasNext()) {
                    String rawMsg = input.next();
                    String receiveMsg = rawMsg.trim();
                    System.out.println("[receive from client]:" + receiveMsg);
                    if ("quit".equals(receiveMsg)) {
                        flag = false;
                        System.out.println("quiting...");
                    } else {
                        output.println(String.format("ECHO-%s", receiveMsg));
                    }
                }
            }
            System.out.println("service stop.");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
